package com.kun.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.kun.entity.Role;
import com.kun.entity.RoleExample;
import com.kun.entity.UserRole;
import com.kun.entity.UserRoleExample;
import com.kun.mapper.cluster.custom.RoleMapperRCustom;
import com.kun.mapper.master.MasterUserRoleMapper;
import com.kun.service.RolePermissionService;
import com.kun.util.PaginationUtil;

/**
 * @description: 角色权限Service
 * @author: KM
 * 2018年5月9日 下午5:24:29
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService {
	
	@Autowired
	private RoleMapperRCustom roleMapperRCustom;
	
	@Autowired
	private MasterUserRoleMapper masterUserRoleMapper;
	
	/**
	 * 根据userId查询角色权限
	 * */
	public List<Role> selectRoleAndPermissionByUserId(String userId){
		return roleMapperRCustom.selectRoleAndPermissionByUserId(userId);
	}

	/**
	 * 查询所有角色
	 * */
	public Map<String,Object> selectAllRole(int begin,int length,String jsonString){
		RoleExample example = new RoleExample();
		if(!"".equals(jsonString)&&jsonString!=null&&jsonString.length()>0){
			JSONObject json = JSONObject.parseObject(jsonString);
			@SuppressWarnings("rawtypes")
			Map cMap = (Map)json;
			if (cMap != null && !cMap.isEmpty()) {
				@SuppressWarnings("rawtypes")
				Iterator it = cMap.keySet().iterator();
				while(it.hasNext()){
					String name = (String)it.next();
					if(!cMap.get(name).equals(null)){
						if(name.equals("type")){//类型查询
							//criteria.andTypeidLike(cMap.get(name) + "%");
						}
					}
				}
			}
		}
		
		int allRecord = roleMapperRCustom.countByExample(example);
		PaginationUtil pagination = new PaginationUtil((begin-1)*length,length,allRecord);
		example.setPagination(pagination);
		List<Role> roleList = roleMapperRCustom.selectByExample(example);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("allRecord", allRecord);
		resultMap.put("roleList", roleList);
		return resultMap;
	}
	
	/**
	 * 给用户添加角色
	 * */
	public int insertUserRole(String userId,int roleId){
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		userRole.setRoleId(roleId);
		return masterUserRoleMapper.insertSelective(userRole);
	}
	
	/**
	 * 删除用户的角色
	 * */
	public int deleteUserRole(String userId,int roleId){
		UserRoleExample ue = new UserRoleExample();
		UserRoleExample.Criteria c = ue.createCriteria();
		c.andUserIdEqualTo(userId);
		c.andRoleIdEqualTo(roleId);
		return masterUserRoleMapper.deleteByExample(ue);
	}
	
}
